#encoding:utf-8
#https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group,Permission,ContentType
from apps.news.models import News,NewsCategory,Banner,Comment
from apps.course.models import Teacher,Course,CourseCategory,CourseOrder
from apps.payinfo.models import Payinfo,PayinfoOrder


class Command(BaseCommand):
     def handle(self, *args, **options):
        #目标创建三个分组
        #1.编辑组  新闻 课程 轮播图 评论
        #根据模型找到对应的content_type_id
        edit_content_types = [
            ContentType.objects.get_for_model(News),
            ContentType.objects.get_for_model(NewsCategory),
            ContentType.objects.get_for_model(Banner),
            ContentType.objects.get_for_model(Comment),
            ContentType.objects.get_for_model(Course),
            ContentType.objects.get_for_model(CourseCategory),
            ContentType.objects.get_for_model(Teacher),
            ContentType.objects.get_for_model(Payinfo),
        ]
        #获取模型对应的权限
        edit_permissions=Permission.objects.filter(content_type__in=edit_content_types)
        edit_group = Group.objects.create(name='编辑')#创建组
        edit_group.permissions.set(edit_permissions)
        edit_group.save()
        self.stdout.write(self.style.SUCCESS('编辑组创建完成'))
        #2.财务  课程、付费资讯订单
        finance_content_types = [
            ContentType.objects.get_for_model(CourseOrder),
            ContentType.objects.get_for_model(PayinfoOrder),
        ]
        finance_permissions = Permission.objects.filter(content_type__in=finance_content_types)
        finance_group = Group.objects.create(name='财务')  # 创建组
        finance_group.permissions.set(finance_permissions)
        finance_group.save()
        self.stdout.write(self.style.SUCCESS('财务组创建完成'))
        #3.管理员组  编辑组+财务组
        admin_permissions = edit_permissions.union(finance_permissions)
        admin_group = Group.objects.create(name='管理员')  # 创建组
        admin_group.permissions.set(admin_permissions)
        admin_group.save()


        #4.超级管理员
        self.stdout.write(self.style.SUCCESS('超级管理员创建成功'))
